<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once('MP_Cache.php');
Class ObjectCache_helper{
	protected $objects = array();
	protected static $instance = null;
	protected static $disableCache = false;
	
	protected $mp_cache;
	
	const DEFAULT_EXPIRE_TIME = 3000;
	
	
	private function __construct(){
		if(self::$disableCache){
			//caching disable
			return;
		}
		$this->objects = array();
		$this->mp_cache = new MP_Cache();
		return;
	}
	public function write($key, $obj, $expire = 0){
		$this->objects[$key] = $obj;
		$this->mp_cache->write($obj, $key, $expire);
	}
	
	public static function getInstance(){
		if(is_null(self::$instance)){
			self::$instance = new ObjectCache_helper();
		}
		return self::$instance;
	}
	public static function reset(){
		self::$instance->delete_all(null);
		self::$instance = null;
	}
	public static function enableCache(){
		self::$disableCache = false;
	}
	public static function disableCache(){
		self::$disableCache = true;
	}
	public static function register($obj){
		if(self::$disableCache){
			//caching disable
			return;
		}
		$key = self::getKey(get_class($obj), $obj->getId());
		self::getInstance()->write($key, $obj);
	}
	/**
	 * 
	 * @param string $classname
	 * @param id $id
	 */
	public static function hasObject($classname, $id){
		$key = self::getKey($classname, $id);
		if((isset(self::getInstance()->objects[$key]))){
			return true;
		}
		if(self::getInstance()->mp_cache->get($key)){
			self::getInstance()->objects[$key] = self::getInstance()->mp_cache->get($key);
		}
		return false;
	}
	public static function getObject($classname, $id){
		$key = self::getKey($classname, $id);
		return self::getInstance()->objects[$key];
	}
	protected static function getKey($classname, $id){
		return md5($classname . $id);
	}
	public static function unregister($obj){
		$key = self::getKey(get_class($obj), $obj->getId());
		if((isset(self::getInstance()->objects[$key]))){
			unset(self::getInstance()->objects[$key]);
		}
		self::getInstance()->mp_cache->delete($key);
	}
}